package springboot.springboot06_ssmp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;
import springboot.springboot06_ssmp.entity.Role;
import springboot.springboot06_ssmp.entity.RoleMenu;
import springboot.springboot06_ssmp.mapper.RoleMapper;
import springboot.springboot06_ssmp.mapper.RoleMenuMapper;
import springboot.springboot06_ssmp.service.IRoleService;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author daiqiang
 * @since 2024-06-16
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private RoleMenuMapper roleMenuMapper;


    @Override   //分页，模糊查询
    public IPage<Role> getPage(int currentPage, int pageSize, Role role) {
        LambdaQueryWrapper<Role> lqw = new LambdaQueryWrapper<>();
        lqw.like(Strings.isNotEmpty(role.getRoleName()),Role::getRoleName,role.getRoleName());



        IPage page = new Page(currentPage,pageSize);
        roleMapper.selectPage(page,lqw);
        return  page;

    }

    @Override
    @Transactional
    public void addRole(Role role) {
        //写入角色表
        this.baseMapper.insert(role);
        //写入角色菜单关系表
        if(role.getMenuIdList()!=null){
            for (Integer menuId:role.getMenuIdList()){
                roleMenuMapper.insert(new RoleMenu(null,role.getRoleId(),menuId));  //一个角色可以有多个菜单
            }
        }
    }
    @Override
    public Role getRoleById(Integer id) {
        Role role=this.baseMapper.selectById(id);
       List<Integer>  menuIdlist = roleMenuMapper.getMenuIdListByRoleId(id);
       role.setMenuIdList(menuIdlist);
        return role;
    }
    @Transactional
    @Override
    public void updateRole(Role role) {
        //修改角色表
        this.baseMapper.updateById(role);
        //删除角色菜单关系表
        LambdaQueryWrapper<RoleMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RoleMenu::getRoleId,role.getRoleId());
        roleMenuMapper.delete(wrapper);
        //写入角色菜单关系表
        if(role.getMenuIdList()!=null){
            for (Integer menuId:role.getMenuIdList()){
                roleMenuMapper.insert(new RoleMenu(null,role.getRoleId(),menuId));
            }
        }

    }
    @Transactional
    @Override
    public void deleteRoleById(Integer id) {
        //1.删除角色表
        //2.删除角色菜单表
        this.baseMapper.deleteById(id);
        LambdaQueryWrapper<RoleMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RoleMenu::getRoleId,id);
        roleMenuMapper.delete(wrapper);
    }

}
